﻿using ExcelDataReader;
using S7.Net;
using S7.Net.Types;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace S7NetManager.Reader
{
    public static class ReaderExtension
    {
        public static IEnumerable<DataItemEntity> ReadFromExcel(this Stream stream)
        {
            using (var reader = ExcelReaderFactory.CreateReader(stream))
            {
                do
                {
                    while (reader.Read())
                    {
                        yield return new DataItemEntity
                        {
                            Id = int.Parse(reader.GetValue(0).ToString()),
                            DB = int.Parse(reader.GetValue(1).ToString().Replace("DB", string.Empty)),
                            DataType = reader.GetValue(2).ToString() == "M" ? DataType.Memory : DataType.DataBlock,
                            StartByteAdr = int.Parse(reader.GetValue(3).ToString()),
                            VarType = (VarType)Enum.Parse(typeof(VarType), reader.GetValue(4).ToString()),
                            BitAdr = byte.Parse(reader.GetValue(5).ToString()),
                            Name = reader.GetValue(6).ToString(),
                        };                    
                    }
                } while (reader.NextResult());
            }
        }



        public static Task<IEnumerable<DataItemEntity>> ReadFromExcelAsync(this Stream stream)
         => Task.Run(() => ReadFromExcel(stream));
    }
}
